package cn.com.pureAppApi.interceptor;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;

import cn.com.pureAppApi.exception.ResponseCodeEnum;
import cn.com.pureAppApi.exception.ResponseException;
import io.swagger.annotations.Authorization;

/**
 * QQ讨论群:76989293
 * @email 2696701142@qq.com
 * @date 2018-06-12 16:51:48
 *
 */
public class WebHandlerInterceptorAdapter extends HandlerInterceptorAdapter {
	final static Log logger = LogFactory.getLog(WebHandlerUtil.class);


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader(HeaderEnum.TOKEN.getKey());
		if (token == null) {
			if (request.getSession().getAttribute("token") != null) {
				token = request.getSession().getAttribute("token").toString();
			} else {
				if (request.getCookies() != null) {
					for (Cookie cookie : request.getCookies()) {
						if (cookie.getName().equals("token"))
							token = cookie.getValue();
					}
				}
			}
		}
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			RequestHeader header = WebHandlerUtil.preHandle(request, response, handler);

			// 获取用户id
			this.parseTokenToUserId(request, response, header, method, token);

			// 打印日志
			this.printLog(request, response, header);

		}
		return true;
	}

	
	/**
	 * 打印日志
	 */
	private void printLog(HttpServletRequest request, HttpServletResponse response, RequestHeader header) {
		Integer terminal = request.getIntHeader(HeaderEnum.TERMINAL.getKey());
		String version = request.getHeader(HeaderEnum.VERSION.getKey());
		String imei = request.getHeader(HeaderEnum.IMEI.getKey());
		String ua = request.getHeader(HeaderEnum.UA.getKey());
		String sysVersion = request.getHeader(HeaderEnum.SYSVERSION.getKey());
		Integer networkOper = request.getIntHeader(HeaderEnum.NETWORK_OPER.getKey());
		Integer networkStatus = request.getIntHeader(HeaderEnum.NETWORK_STATUS.getKey());
		String outsourceSign = request.getHeader(HeaderEnum.OUTSOURCE_SIGN.getKey());
		StringBuffer sb = new StringBuffer();
		String ip = ClientHostUtil.getIpAddress(request);
		sb.append("[");
		sb.append("[ip:");
		sb.append(ip);
		sb.append("]");
		sb.append("[REQUEST_URL:");
		sb.append(request.getRequestURI());
		sb.append("]");
		sb.append("[用户id:");
		sb.append(request.getAttribute("userId"));
		sb.append("]");
		sb.append("[REQUEST_PARAM:");
		sb.append(JSON.toJSONString(request.getParameterMap()));
		sb.append("]");
		sb.append("请求拦截日志：[客户端:");
		sb.append(terminal);
		sb.append("][版本:");
		sb.append(version);
		sb.append("][客户端唯一识别号:");
		sb.append(imei);
		sb.append("][手机型号:");
		sb.append(ua);
		sb.append("][手机系统版本号:");
		sb.append(sysVersion);
		sb.append("][网络运营商(1、移动2联通3电信4其他):");
		sb.append(networkOper);
		sb.append("][网络状态（1蜂窝、2、wifi）:");
		sb.append(networkStatus);
		sb.append("][外包交互sign 签名:");
		sb.append(outsourceSign);
		sb.append("]");
		sb.append("]");
		logger.info(sb);
		logger.info("访问机型：" + ua);
		//添加访问次数统计		
	}

	/**
	 * 存储用户id和手机号
	 * 
	 * @param request
	 * @param header
	 * @param method
	 * @param token
	 */
	private void parseTokenToUserId(HttpServletRequest request, HttpServletResponse response, RequestHeader header,
			Method method, String token) {
		Authorization authorization = method.getAnnotation(Authorization.class);
		if (authorization != null && StringUtils.isEmpty(token)) {
            throw new ResponseException(ResponseCodeEnum.UNAUTHORIZED);
		} else {
			if (StringUtils.isEmpty(token)) {
				request.setAttribute("userId", "0");
				return;
			}
//			if (stringRedisTemplate == null) {
//				BeanFactory factory = WebApplicationContextUtils
//						.getRequiredWebApplicationContext(request.getServletContext());
//				stringRedisTemplate = factory.getBean(StringRedisTemplate.class);
//			}
//			BoundHashOperations<String, String, String> boundHashOperations = stringRedisTemplate.boundHashOps(token);
//			Map<String, String> data = boundHashOperations.entries();
			Map<String, String> data =new HashMap<String, String>();
			if (!org.apache.commons.collections.MapUtils.isEmpty(data)) {
				if (authorization != null) {
//					request.setAttribute(authorization.paramName(), data.get("userId"));
				} else {
					request.setAttribute("userId", data.get("userId"));
				}
				request.setAttribute("telphone", data.get("telphone"));
				if (header != null) {
					header.setUserId(Integer.parseInt(data.get("userId")));
					header.setTelphone(data.get("telphone"));
				}
			} else {
				if (authorization != null) {
					throw new ResponseException(ResponseCodeEnum.UNAUTHORIZED);
				}
			}
		}
	}

	

}
